﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using OnlineCooperation.Entity;
using OnlineCooperation.DB;
using System.Text;
using System.Net.Mail;

namespace OnlineCooperation
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["UserEmail"] != null && Session["UserPwd"] != null)
            {
                RememberState.Checked = true;
                LoginMethod(Session["UserEmail"].ToString(), Session["UserPwd"].ToString());
                return;
            }

            HttpCookie aCookie = new HttpCookie("email");
            aCookie = Request.Cookies["email"];
            HttpCookie bCookie = new HttpCookie("password");
            bCookie = Request.Cookies["password"];


            if (aCookie != null && bCookie != null)
                if (aCookie.Value != "" && bCookie.Value != "")
                {
                    RememberState.Checked = true;
                    string email = aCookie.Value;
                    string pwd = bCookie.Value;
                    LoginMethod(email, pwd);
                }
        }

        protected void ButtonLoginClick(object sender, EventArgs e)
        {
            LoginMethod(InputEmail.Value, InputPwd.Value);
        }

        private void LoginMethod(string email, string pwd)
        {
            UserDB ud = new UserDB();
            User u = ud.GetUserByEmail(email);
            if (u.ID == -1)
            {
                Response.Write("<script>alert('用户不存在！')</script>");
                return;
            }

            if (u.Pwd != pwd)
            {
                Response.Write("<script>alert('输入密码不正确！')</script>");
                return;
            }
            Session["UserID"] = u.ID;
            Session["UserName"] = u.Name;
            Session["UserEmail"] = u.Email;

            if (RememberState.Checked == true)//如果要求记住密码，就记录cookie
            {       
                //向客户端浏览器加入Cookie （email和密码 最好是使用MD5加密）
                Response.Cookies["email"].Value = u.Email;
                Response.Cookies["email"].Expires = DateTime.Now.AddMonths(1);

                Response.Cookies["password"].Value = u.Pwd;
                Response.Cookies["password"].Expires = DateTime.Now.AddMonths(1);
            }
            else
            {
                Response.Cookies["email"].Expires = DateTime.Now.AddMonths(-1);
                Response.Cookies["password"].Expires = DateTime.Now.AddMonths(-1);
            }

            Response.Redirect("HomePageJump.aspx");
        }

        public void SendSMTPEMail(string strSmtpServer, string strFrom, string strFromPass, string strto, string strSubject, string strBody)
        {
            System.Net.Mail.SmtpClient client = new SmtpClient(strSmtpServer);
            client.UseDefaultCredentials = false;
            client.Credentials = new System.Net.NetworkCredential(strFrom, strFromPass);
            client.DeliveryMethod = SmtpDeliveryMethod.Network;

            System.Net.Mail.MailMessage message = new MailMessage(strFrom, strto, strSubject, strBody);

            message.BodyEncoding = System.Text.Encoding.UTF8;
            message.IsBodyHtml = true;
            client.Port = 587;
            client.EnableSsl = true;
            client.Send(message);
        }

        protected void ButtonForgotSendEmailClick(object sender, EventArgs e)
        {
            //先根据用户名判断该用户是否存在                   
            UserDB ud = new UserDB();
            String CurrentEmail = UserEmailAdd.Value;
            if (CurrentEmail == null)
            {
                Response.Write("<script>alert('请先输入邮箱哦~')</script>");
                return;
            }
            User u = ud.GetUserByEmail(CurrentEmail);
            if (u.ID == -1)
            {
                Response.Write("<script>alert('用户不存在！')</script>");
                return;
            }
            //生成随机字符串
            String RamPwd = System.Guid.NewGuid().ToString().Substring(0, 6);
            //在数据库中修改用户密码
            u = new User(u.ID, u.Name, CurrentEmail, RamPwd, u.Icon);
            ud.Update(u);
            //发送邮件给用户
            char myreturn = '\n';
            String MailContent = "尊敬的用户，您好:" + myreturn.ToString();
            MailContent += "您在CoCo（在线协作平台）网站点击了“忘记密码”按钮，故系统自动为您发送了这封邮件。请使用您的用户名，以随机字符串";
            MailContent += RamPwd;
            MailContent += "作为密码登录CoCo。";
            MailContent += myreturn.ToString();
            MailContent += "温馨提醒：不要忘记及时修改您的密码哦~";
            MailContent += myreturn.ToString();
            MailContent += "如果您不需要修改密码，或者您从未点击过“忘记密码”按钮，请忽略本邮件。";
            SendSMTPEMail("smtp.gmail.com", "huangyg11@gmail.com", "zkegtomkpztvnvib", CurrentEmail, "CoCo助您找回密码", MailContent);
              
         }
    }
}